#coding: utf-8


import sys
import os.path 

cur_path = os.path.dirname(__file__)
parent_path = os.path.abspath(os.path.join(cur_path, '..'))
sys.path.append(parent_path)

import time
import pymongo
from topapi import *
from exceptions import Exception



def check_expire(uobj, user):
    try:
        uinfo = uobj.get(user['top_session'], user['_id'])
    except Exception as e:
        einfo = e.args[0]
        if 27 == einfo[0] and 'Session expired' in einfo[1]:
            return None
        else:
            raise
    return uinfo


def test_check_expire():
    user = {
            'top_session':'6100b16676d650aae0d0c9e81145ebef56c4b2be4bb5aae741880263',
            '_id':'威拉帝莎旗舰店',
    }
    uobj = User()
    print check_expire(uobj, user)
    user = {
            'top_session': '6102913ac40371450afba119d38da5e95027010711720ef409817434', 
            '_id': 'liang_g6686'}
    print check_expire(uobj, user)


def check_and_update(db, uobj, user):
    uinfo = check_expire(uobj, user)
    if uinfo:
        uinfo = uinfo['user']
        db.user.update({'_id':user['_id']}, {'$set':uinfo}, safe=True)
    else:
        db.user.update({'_id':user['_id']}, {'$set':{'status':'expired'}})

        
def traverse_and_check(mdb):
    skip = 0
    limit = 1000
    user_obj = User()
    while True:
        cur = mdb.user.find(fields = ['top_session', ], timeout=False).skip(skip).limit(limit)
        cur.batch_size(200)
        if cur.count(True) <= 0:
            print 'traverse finish'
            break
        for u in cur:
            try:
                check_and_update(mdb, user_obj, u)
            except Exception as e:
                print 'checking and update user fail: %s, %s' %(u['_id'].encode('utf8'), repr(e))
                continue
            print 'checked: %s' %(u['_id'].encode('utf8'))
        skip += limit

if __name__ == '__main__':
    m = pymongo.Connection('127.0.0.1:57324')
    db = m.taogold
    traverse_and_check(db)


